home *** CD-ROM | disk | FTP | other *** search
/ Aminet 40 / Aminet 40 (2000)(Schatztruhe)[!][Dec 2000].iso / Aminet / dev / lang / Python16_Src.lha / Python16_Source / Demo / embed / demo.c next >
Encoding:
C/C++ Source or Header  |  1999-03-10  |  1.6 KB  |  70 lines

  1. /* Example of embedding Python in another program */
  2.  
  3. #include "Python.h"
  4.  
  5. void initxyzzy(); /* Forward */
  6.  
  7. main(argc, argv)
  8.     int argc;
  9.     char **argv;
  10. {
  11.     /* Pass argv[0] to the Python interpreter */
  12.     Py_SetProgramName(argv[0]);
  13.  
  14.     /* Initialize the Python interpreter.  Required. */
  15.     Py_Initialize();
  16.  
  17.     /* Add a static module */
  18.     initxyzzy();
  19.  
  20.     /* Define sys.argv.  It is up to the application if you
  21.        want this; you can also let it undefined (since the Python 
  22.        code is generally not a main program it has no business
  23.        touching sys.argv...) */
  24.     PySys_SetArgv(argc, argv);
  25.  
  26.     /* Do some application specific code */
  27.     printf("Hello, brave new world\n\n");
  28.  
  29.     /* Execute some Python statements (in module __main__) */
  30.     PyRun_SimpleString("import sys\n");
  31.     PyRun_SimpleString("print sys.builtin_module_names\n");
  32.     PyRun_SimpleString("print sys.modules.keys()\n");
  33.     PyRun_SimpleString("print sys.executable\n");
  34.     PyRun_SimpleString("print sys.argv\n");
  35.  
  36.     /* Note that you can call any public function of the Python
  37.        interpreter here, e.g. call_object(). */
  38.  
  39.     /* Some more application specific code */
  40.     printf("\nGoodbye, cruel world\n");
  41.  
  42.     /* Exit, cleaning up the interpreter */
  43.     Py_Exit(0);
  44.     /*NOTREACHED*/
  45. }
  46.  
  47. /* A static module */
  48.  
  49. static PyObject *
  50. xyzzy_foo(self, args)
  51.     PyObject *self; /* Not used */
  52.     PyObject *args;
  53. {
  54.     if (!PyArg_ParseTuple(args, ""))
  55.         return NULL;
  56.     return PyInt_FromLong(42L);
  57. }
  58.  
  59. static PyMethodDef xyzzy_methods[] = {
  60.     {"foo",        xyzzy_foo,    1},
  61.     {NULL,        NULL}        /* sentinel */
  62. };
  63.  
  64. void
  65. initxyzzy()
  66. {
  67.     PyImport_AddModule("xyzzy");
  68.     Py_InitModule("xyzzy", xyzzy_methods);
  69. }
  70.